package protocol

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"gitee.com/ldysdy999/hostdemon/conf"
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"
	"github.com/julienschmidt/httprouter"

	hostAPI "gitee.com/ldysdy999/hostdemon/app/host/http"
)

func NewHTTPService() *HTTPService {
	r := httprouter.New()
	server := &http.Server{
		//读取Head超时设置
		ReadHeaderTimeout: 60 * time.Second,
		//server读取超时
		ReadTimeout: 60 * time.Second,
		//server响应数据超时
		WriteTimeout: 60 * time.Second,
		//tcp复用
		IdleTimeout: 60 * time.Second,
		//最大头
		MaxHeaderBytes: 1 << 20, // 1M
		//监听
		Addr: conf.C().App.Addr(),
		//http handler
		Handler: r,
	}
	return &HTTPService{
		r:      r,
		l:      zap.L().Named("HTTP Server"),
		server: server,
	}
}

type HTTPService struct {
	//root router,路由
	r *httprouter.Router
	//日志
	l logger.Logger
	//服务实例，http服务器
	server *http.Server
}

//启动http服务
func (s *HTTPService) Start() error {
	//加载子服务路由
	//http api服务模块初始化
	hostAPI.Api.Init()
	hostAPI.Api.Registry(s.r)

	//启动http服务
	s.l.Info("HTTP服务启动成功,监听地址:%s", s.server.Addr)
	if err := s.server.ListenAndServe(); err != nil {
		if err == http.ErrServerClosed {
			s.l.Info("server is stopped")
		}
		return fmt.Errorf("start service error, %s", err.Error())
	}
	return nil
}

//关闭http服务
func (s *HTTPService) Stop() error {
	s.l.Info("start graceful shutdown")
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	// 优雅关闭HTTP服务
	if err := s.server.Shutdown(ctx); err != nil {
		s.l.Errorf("graceful shutdown timeout, force exit")
	}
	return nil
}
